package p.ithorns.sample.minio;

import io.minio.ObjectWriteResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import p.ithorns.framework.minio.MinioProperties;
import p.ithorns.framework.minio.MinioTemplate;
import p.ithorns.framework.minio.model.UploadResp;
import p.ithorns.sample.minio.utils.FileUtil;
import p.ithorns.sample.minio.utils.StringUtil;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDate;

/**
 * FileUploadService
 *
 * @author liuhaitao
 * @date 2024/4/8 14:38
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MinioService {

    // 临时文件目录
    private static final String TEMP_FILE_ROOT = "temp";

    private final MinioTemplate minio;

    private final MinioProperties minioProps;


    public String upload(MultipartFile file, Object meta) {
        // 文件名
        String fileName = file.getOriginalFilename();
        File tempFile = buildTempFile(fileName);

        try (InputStream inputStream = file.getInputStream()) {
            // 文件blake3摘要
            String bucketName = minioProps.getBucketName();
            String blake3 = FileUtil.getBlake3(inputStream);
            String contentType = file.getContentType();
            ObjectWriteResponse response = minio.uploadFile(bucketName, blake3, contentType, inputStream);
            return UploadResp.wrap(response).toString();
        } catch (Exception e) {
            log.error("上传失败", e);
            return e.getMessage();
        }
    }

    private File buildTempFile(String fileName) {
        String path = TEMP_FILE_ROOT + File.separator + fileName;
        return FileUtil.createFile(path);
    }

    private String buildDateSegFilePath(String fileName) {
        String SEPARATOR = "/";
        LocalDate date = LocalDate.now();
        String suffix = StringUtil.substringAfterLast(fileName, ".");
        return date.getYear() + SEPARATOR
                + date.getMonthValue() + SEPARATOR
                + date.getDayOfMonth() + SEPARATOR
                + fileName + suffix;
    }

    public InputStream download(String fileName) throws Exception {
        return minio.getObject(minioProps.getBucketName(), fileName);
    }

    public void remove(String fileName) throws Exception {
        minio.remove(minioProps.getBucketName(), fileName);
    }

    public String getStatus(String fileName) throws Exception {
        return minio.getObjectStatus(minioProps.getBucketName(), fileName);
    }

    public String getUrl(String fileName) throws Exception {
        return minio.getObjectUrl(minioProps.getBucketName(), fileName);
    }

}